<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search">
				<el-input size="default" class="w_150 mb15 mr10" v-model="listQuery.SubSystemName" placeholder="子系统名称" @keydown.enter="searchForm">
				</el-input>
				<el-input size="default" class="w_150 mb15 mr10" v-model="listQuery.InterfaceName" placeholder="接口名称" @keydown.enter="searchForm">
				</el-input>
				<el-button size="default" @click="searchForm" type="primary" class="mr10 mb15"> 查询 </el-button>
				<el-button size="default" type="success" class="mr10 mb15" @click="addRule"> 新增 </el-button>
				<el-button size="default" type="info" class="mr10 mb15" @click="resetForm"> 重置 </el-button>
			</div>
			<tableTem ref="tableRef" v-bind:="state.tableData" @pageChange="onTablePageChange">
				<el-table-column align="center" type="index" label="序号" width="60" />
				<el-table-column align="center" min-width="120" prop="modelName" label="模型名称"></el-table-column>
				<el-table-column align="center" min-width="120" prop="subSystemName" label="子系统名称"></el-table-column>
				<el-table-column align="center" prop="interfaceName" min-width="150" label="接口名称"></el-table-column>
				<el-table-column align="center" prop="createTime" min-width="120" label="创建时间"></el-table-column>

				<el-table-column label="操作" align="center" width="190" fixed="right">
					<template #default="scope">
						<el-button size="small" type="primary" text @click="editOption(scope.row)">编辑</el-button>
						<el-button size="small" type="primary" text @click="onRowDel(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</tableTem>
		</div>
		<!-- 弹窗 -->
		<el-dialog
			:title="state.isEdit ? '编辑模型应用' : '新增模型应用'"
			v-model="state.dialogVisible"
			:close-on-click-modal="false"
			:show-close="false"
			:close-on-press-escape="false"
			width="500px"
		>
			<el-form class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="APPKEY" prop="appkey">
							<el-select class="w_250 mr10" @change="GetFun" v-model="state.ruleForm.appkey" size="default">
								<el-option v-for="item in state.infoList" :key="item.id" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="接口(API)" prop="functionId">
							<el-select class="w_250 mr10" v-model="state.ruleForm.functionId" size="default">
								<el-option v-for="item in state.functionList" :key="item.id" :label="item.functionDisplayName" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="dialog-btn">
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import { RiskApiModelGetPagedList, RiskApiModelDelete, RiskApiModelCreate, RiskApiModelUpdate, RiskApiModelId } from '/@/api/model/index';
import { SubSystemGetPagedList } from '/@/api/subSystemInfo/index';
// 引入组件
const tableTem = defineAsyncComponent(() => import('/@/components/tables/index.vue'));
// 定义父组件传过来的值
const props = defineProps({
	modelId: {
		type: [Number, String],
		default: () => '',
	},
});
// 定义变量内容
const tableRef = ref();
const modelListFef = ref();
const listQuery = reactive({
	SubSystemName: '', //名称
	InterfaceName: '', //名称
});
const state = reactive<any>({
	tableData: {
		data: [],
		total: 0,
		loading: true,
		param: {
			PageIndex: 1,
			PageSize: 10,
		},
	},
	infoList: [],
	functionList: [],
	ruleForm: {
		appkey: '',
		functionId: '',
		id: '',
	} as any, // 新增
	dialogVisible: false, // 弹窗状态
	isEdit: false, //是否编辑
});
// 页面加载时
onMounted(() => {
	getTableData();
});

// 初始化表格数据
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const params = {
			...state.tableData.param,
			...listQuery,
			modelId: props.modelId,
		};
		Object.keys(params).forEach((key) => {
			if (!params[key]) delete params[key];
		});
		let data = await RiskApiModelGetPagedList(params);
		state.tableData.data = data.data.items;
		state.tableData.total = data.data.totalCount;
	} finally {
		state.tableData.loading = false;
	}
};

// 新增
const addRule = () => {
	state.ruleForm.appkey = '';
	state.ruleForm.functionId = '';
	state.dialogVisible = true;
	state.isEdit = false;
	GetFieldTypes();
};
// 编辑
const editOption = async (item: any) => {
	GetFieldTypes();
	state.ruleForm.functionId = item.functionId;
	state.ruleForm.id = item.id;
	if (state.infoList.length) {
		state.infoList.forEach(async (v: any) => {
			if (item.appkey == v.appKey) {
				state.ruleForm.appkey = v.id;
				let data = await RiskApiModelId(v.id);
				state.functionList = data.data;
				state.ruleForm.functionId = item.functionId;
			}
		});
	}
	state.dialogVisible = true;
	state.isEdit = true;
};

// 删除账户
const onRowDel = (id: any) => {
	ElMessageBox.confirm(`此操作将永久删除模型应用信息，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await RiskApiModelDelete([id]);
		ElMessage.success('删除成功');
		getTableData();
	});
};
// 分页改变
const onTablePageChange = (val: any) => {
	state.tableData.param.PageIndex = val.pageNum;
	state.tableData.param.PageSize = val.pageSize;
	getTableData();
};
// 搜索点击时表单回调
const searchForm = () => {
	state.tableData.param.PageIndex = 1;
	tableRef.value.pageReset();
};
// 重置
const resetForm = () => {
	listQuery.SubSystemName = '';
	listQuery.InterfaceName = '';
	searchForm();
};

// 关闭弹窗
const onCancel = () => {
	state.dialogVisible = false;
};

const rules = reactive({
	appkey: [{ required: true, message: '请选择APPKEY', trigger: ['blur', 'change'] }],
	functionId: [{ required: true, message: '请选择接口(API)', trigger: ['blur', 'change'] }],
});
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
				modelId: props.modelId,
			};
			if (state.infoList.length) {
				state.infoList.forEach((v: any) => {
					if (params.appkey == v.id) {
						params.appkey = v.appKey;
					}
				});
			}
			if (state.isEdit) {
				await RiskApiModelUpdate(params, state.ruleForm.id);
			} else {
				delete params.id;
				await RiskApiModelCreate(params);
			}
			ElMessage.success(state.isEdit ? '修改成功' : '新增成功');
			onCancel();
			resetForm();
		}
	});
};
//  appkey
const GetFieldTypes = async () => {
	let data = await SubSystemGetPagedList({ PageIndex: 1, PageSize: 9999 });
	state.infoList = data.data.items;
};
//  接口
const GetFun = async (v: any, type: any) => {
	if (type == 1) {
		state.functionList = [];
		state.ruleForm.functionId = '';
	}

	let data = await RiskApiModelId(v);
	state.functionList = data.data;
};
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
.layout-padding {
	padding: 0 15px 15px 15px !important;
	width: 100%;
}
</style>
